﻿using UnityEngine;
using System.Collections;

public class PhysEarthquake : MonoBehaviour {

	public GameObject target;

	public float duration = 5.0f;
	public float displacement = 0.50f;
	public float chaos = 1.0f;
	public float magnitude = 10.0f;

	private float timer = 0;

	public void earthquake(float mag) {
		if (mag != 0) magnitude = mag;
		timer = duration;
	}
		
	// Update is called once per frame
	void FixedUpdate () {
		timer -= Time.fixedDeltaTime;
		if (timer <= 0) {
			timer = 0;
		} else {

			float t = chaos * timer;
			float a = Mathf.Sin (t * Mathf.PI*2 * 2);
			float b = Mathf.Cos (t * Mathf.PI*2 * 3)/2 + 0.5f;
			float c = Mathf.Sin (t * Mathf.PI*2 * 5)/2 + 0.5f;
			float a1 = Mathf.Cos (t * Mathf.PI*2 * 2.123f)/2 + 0.5f;
			float a2 = Mathf.Sin (t * Mathf.PI*2 * 3.123f)/2 + 0.5f;
			float a3 = Mathf.Sin (t * Mathf.PI*2 * 5.123f);
			float a4 = Mathf.Sin (t * Mathf.PI*2 * 7.123f);

			Vector3 d = Vector3.up * magnitude * displacement;
			d = Quaternion.Euler(a * 360, (b+a3/2) * 360, (c+a4) * 360) * d;
			d = d * (a3 + a4 + 4)/6;

			float ft = Mathf.Clamp01(timer / duration);
			d = d * (1.0f - Mathf.Abs (1 - ft*2));

			if (target == null) {
				transform.localPosition = d; 
			} else {
				Vector3 p = target.transform.localPosition;
				Vector3 delta = d - p;
				delta = (delta * 1.0f / Time.fixedDeltaTime);
				float deltasqrmag = delta.sqrMagnitude;
				float cx = chaos * displacement;
				if (deltasqrmag > cx*cx) delta = delta * (cx / Mathf.Sqrt(deltasqrmag));
				d = p + delta;
				target.transform.localPosition = d;
			}


		}
	}
}
